//
//  BzVC+API.swift
//  Auscultation
//
//  Created by 来 on 2021/1/6.
//

import Foundation

// 接口
extension BzVC {
    
    func getData1(_ call: @escaping (() -> Void)) {
        let paramet: [String: Any] = [
//            "operator": EWEUser.lgf.userId ?? "",
            "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
        ]
        
        EWERequest.lgf("sample/" + id, paramet, .get) { [weak self] (data) in
            self?.sampleDetail = data["sampleDetail"] as? [String: Any] ?? [:]
            
            self?.ph_view_i.lgf_setImage((self?.sampleDetail?["wavPowerPics"] as? String) ?? "")
            let bs: Double = pow(2, 5)
            self?.ph_view_i_w = CGFloat(1920.0 * bs / 2.0)
            self?.ph_view.contentSize = CGSize.init(width: self!.ph_view_i_w, height: self!.ph_view.lgf_Height)
            self?.sp_view.snp.updateConstraints { (make) in
                make.width.equalTo(self!.ph_view_i_w)
            }
            self?.ph_view_i.snp.updateConstraints { (make) in
                make.width.equalTo(self!.ph_view_i_w)
            }
            self?.ph_view_i_top.snp.updateConstraints { (make) in
                make.width.equalTo(self!.ph_view_i_w)
            }
            self?.play_line.maximumValue = Float(((self?.sampleDetail?["duration"] as? Int) ?? 0) / 1000)
            self?.play_time_all.text = "/" + (self?.player.getAllTime(Int(self?.play_line.maximumValue ?? 0) * 1000) ?? "00:00")
            self?.wavPath = EWEUrl.File_URL + ((self?.sampleDetail?["wavPath"] as? String) ?? "")
            self?.wavDataPath = ((self?.sampleDetail?["wavDataPath"] as? String) ?? "")
            self?.reportPath = EWEUrl.File_URL + ((self?.sampleDetail?["reportPath"] as? String) ?? "")
            
            self?.labelId = (data["labelId"] as? String) ?? ""
            self?.auditId = (data["auditId"] as? String) ?? ""
//            self?.auditStatus = (data["auditStatus"] as? Int) ?? 0
//            self?.labelStatus = (data["labelStatus"] as? Int) ?? 0
            self?.isArbitration = (data["isArbitration"] as? Int) ?? 0
            self?.diagnose = (data["auditId"] as? String) ?? ""
            self?.descn = (data["auditId"] as? String) ?? ""
            self?.isDeleted = (data["isArbitration"] as? Int) ?? 0
            
            self?.autoType()
            call()
        } _: { [weak self] (error) in
            SVProgressHUD.showError(error)
            Timer.lgf_After(S: 1.0) {
                self?.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    func getData2(_ userId: String) {
        var paramet2: [String: Any] = [
            "operator": EWEUser.lgf.userId ?? "",
            "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
        ]
        if userId.count == 0 {
            paramet2.removeValue(forKey: "operator")
        }
        var mt: String = ""
        if self.stype == 1 {
            mt = "label/" + self.labelId
        } else if self.stype == 2 {
            mt = "audit/" + self.auditId
        } else if self.stype == 3 {
            mt = "arbitration/" + self.arbitrationId
        } else if self.stype == 4 {
            mt = "label/" + self.labelId
        }
        EWERequest.lgf(mt + "/sample/" + self.id + "/mark" + (self.stype == 3 ? ("/" + self.arbitrationId) : ""), paramet2, .get) { [weak self] (data) in
            if data is [String: Any] {
                self?.bzModel = BzModel()
                self?.bzModel.coordinate = ((data["coordinate"] as? String) ?? "[]").lgf_ToDictionaryArray()
                self?.bzModel.markOption = ((data["markOption"] as? String) ?? "").components(separatedBy: ",")
                self?.bzModel.diagnosis = ((data["diagnosis"] as? String) ?? "").components(separatedBy: ",")
                self?.bzModel.remark = (data["markRemark"] as? String) ?? ""
                self?.bzModel.markId = (data["id"] as? String) ?? ""
                self?.bzModel.isDifficult = (data["isDifficult"] as? Int) ?? 0
                self?.bzModel.isSame = (data["isSame"] as? Int) ?? 0
                self?.bzModel.rating = (data["rating"] as? Int) ?? 0
                self?.bzModel.ratingRemark = (data["ratingRemark"] as? String) ?? ""
                self?.bzModel.operator_ = (data["operator"] as? String) ?? ""
                if self?.stype == 1 {
                    if self?.bzModel.isDifficult == 1 {
                        self?.bzModel.diagnosis.append("疑难样本")
                    }
                    if self?.bzModel.isSame == 1 {
                        self?.bzModel.diagnosis.append("听诊结果与心超报告不符")
                    }
                }
                self?.bzModel.operatorName = (data["operatorName"] as? String ?? "")
                self?.reloadArea(data as! [String : Any])
                if self?.bzModel != nil {
                    self?.creatCoordinate([self!.bzModel!.coordinate])
                }
            } else if data is [[String: Any]] {
                self?.bzModels = []
                let arr = data as! [[String: Any]]
                arr.forEach { (d) in
                    let uid = (d["operator"] as? String) ?? ""
                    if uid == EWEUser.lgf.userId {
                        self?.reloadArea(d)
                    }
                    let model = BzModel()
                    model.coordinate = ((d["coordinate"] as? String) ?? "[[:]]").lgf_ToDictionaryArray()
                    model.markOption = ((d["markOption"] as? String) ?? "").components(separatedBy: ",")
                    model.diagnosis = ((d["diagnosis"] as? String) ?? "").components(separatedBy: ",")
                    model.remark = (d["markRemark"] as? String) ?? ""
                    model.markId = (d["id"] as? String) ?? ""
                    model.isDifficult = (d["isDifficult"] as? Int) ?? 0
                    model.isSame = (d["isSame"] as? Int) ?? 0
                    model.rating = (d["rating"] as? Int) ?? 0
                    model.ratingRemark = (d["ratingRemark"] as? String) ?? ""
                    model.operatorName = (d["operatorName"] as? String) ?? ""
                    model.operator_ = (d["operator"] as? String) ?? ""
                    if model.coordinate.count > 0 {
                        let backgroundColor = UIColor.init(lgf_HexString: (model.coordinate.first?["backgroundColor"] as? String) ?? "F0F0F0")
                        model.backgroundColor = backgroundColor!
                    }
                    self?.bzModels.append(model)
                }
            }
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    func getData5(_ userId: String) {
        var paramet: [String: Any] = [
            "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
        ]
        EWERequest.lgf("label/" + self.labelId + "/sample/" + self.id + "/mark", paramet, .get) { [weak self] (data) in
            if data is [[String: Any]] {
                let arr = data as! [[String: Any]]
                arr.forEach { (d) in
                    let uid = (d["operator"] as? String) ?? ""
                    if uid == EWEUser.lgf.userId {
                        self?.reloadArea(d)
                    }
                    let model = BzModel()
                    model.coordinate = ((d["coordinate"] as? String) ?? "[[:]]").lgf_ToDictionaryArray()
                    model.markOption = ((d["markOption"] as? String) ?? "").components(separatedBy: ",")
                    model.diagnosis = ((d["diagnosis"] as? String) ?? "").components(separatedBy: ",")
                    model.remark = (d["markRemark"] as? String) ?? ""
                    model.markId = (d["id"] as? String) ?? ""
                    model.isDifficult = (d["isDifficult"] as? Int) ?? 0
                    model.isSame = (d["isSame"] as? Int) ?? 0
                    model.rating = (d["rating"] as? Int) ?? 0
                    model.ratingRemark = (d["ratingRemark"] as? String) ?? ""
                    model.operatorName = (d["operatorName"] as? String) ?? ""
                    model.operator_ = (d["operator"] as? String) ?? ""
                    if model.coordinate.count > 0 {
                        let backgroundColor = UIColor.init(lgf_HexString: (model.coordinate.first?["backgroundColor"] as? String) ?? "F0F0F0")
                        model.backgroundColor = backgroundColor!
                    }
                    self?.bzModels.append(model)
                }
                var paramet2: [String: Any] = [
                    "operator": userId,
                    "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
                ]
                if userId.count == 0 {
                    paramet2.removeValue(forKey: "operator")
                }
                EWERequest.lgf("audit/" + self!.auditId + "/sample/" + self!.id + "/mark", paramet2, .get) { [weak self] (data) in
                    if data is [String: Any] {
                        let model = BzModel()
                        model.coordinate = ((data["coordinate"] as? String) ?? "[]").lgf_ToDictionaryArray()
                        model.markOption = ((data["markOption"] as? String) ?? "").components(separatedBy: ",")
                        model.diagnosis = ((data["diagnosis"] as? String) ?? "").components(separatedBy: ",")
                        model.remark = (data["markRemark"] as? String) ?? ""
                        model.markId = (data["id"] as? String) ?? ""
                        model.isDifficult = (data["isDifficult"] as? Int) ?? 0
                        model.isSame = (data["isSame"] as? Int) ?? 0
                        model.rating = (data["rating"] as? Int) ?? 0
                        model.ratingRemark = (data["ratingRemark"] as? String) ?? ""
                        model.operator_ = (data["operator"] as? String) ?? ""
                        model.operatorName = (data["operatorName"] as? String ?? "")
                        if model.coordinate.count > 0 {
                            let backgroundColor = UIColor.init(lgf_HexString: (model.coordinate.first?["backgroundColor"] as? String) ?? "F0F0F0")
                            model.backgroundColor = backgroundColor!
                        }
                        self?.bzModels.append(model)
                    }
                } _: { (error) in
                    SVProgressHUD.showError(error)
                }
            }
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    func reloadArea(_ data: [String: Any]) {
        let first = EVReflection.dictionaryFromJson((data["areaFirst"] as? String) ?? "") as? [String: [String: Any]]
        let second = EVReflection.dictionaryFromJson((data["areaSecond"] as? String) ?? "") as? [String: [String: Any]]
        let third = EVReflection.dictionaryFromJson((data["areaThird"] as? String) ?? "") as? [String: [String: Any]]
        let fourth = EVReflection.dictionaryFromJson((data["areaFourth"] as? String) ?? "") as? [String: [String: Any]]
        let fifth = EVReflection.dictionaryFromJson((data["areaFifth"] as? String) ?? "") as? [String: [String: Any]]
        first?.values.forEach({ (dict) in
            if (dict["type"] as? Int ?? 0) == 1 {
                self.areaFirst = dict
            }
        })
        second?.values.forEach({ (dict) in
            if (dict["type"] as? Int ?? 0) == 1 {
                self.areaSecond = dict
            }
        })
        third?.values.forEach({ (dict) in
            if (dict["type"] as? Int ?? 0) == 1 {
                self.areaThird = dict
            }
        })
        fourth?.values.forEach({ (dict) in
            if (dict["type"] as? Int ?? 0) == 1 {
                self.areaFourth = dict
            }
        })
        fifth?.values.forEach({ (dict) in
            if (dict["type"] as? Int ?? 0) == 1 {
                self.areaFifth = dict
            }
        })
        self.reloadTZQ()
    }
    
    func getData3() {
        // 波形图json
        EWERequest.downloadFile("2", ["path": self.wavDataPath ?? ""], "json") { [weak self] (success) in
            do {
                let jsonString = try String.init(contentsOf: URL.init(fileURLWithPath: success), encoding: .utf8)
                let data = jsonString.lgf_ToDictionary()
                if data.count == 1 {
                    return
                }
//                let duration = data["duration"] as? Int ?? 0
//                let length = data["length"] as? Int ?? 0
                let maxVal = data["maxVal"] as? Int ?? 0
                let array = (((data["data"] as? NSMutableArray)?.firstObject as? NSArray) as? [Any]) ?? []
                var nums: [Double] = []
                array.forEach { (num) in
                    let n = (num as! NSNumber).floatValue
                    let nn = CGFloat(n) / CGFloat(maxVal)
                    nums.append(Double(nn))
                }
                self?.spNums = nums
                self?.reloadLine({ (i, sp) in
                    let l = (i * self!.spNums.count / 100)
                    let r = ((i + 1) * self!.spNums.count / 100)
                    let nums = Array(self!.spNums[l..<r])
                    sp.show(nums, 10)
                })
            } catch {
                SVProgressHUD.showError("数据下载失败")
            }
        } _: { (error) in
            SVProgressHUD.showError("数据下载失败")
        }
    }
    
    func getData4() {
        // 字典
        let paramet2: [String: Any] = [
            "groupCode": "SAMPLE_MARK_OPTION",
        ]
        EWERequest.lgf("dictionary", paramet2, .get) { [weak self] (data) in
            self?.bznrArr = data["result"] as? [[String: Any]] ?? []
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
        let paramet4: [String: Any] = [
            "groupCode": "SAMPLE_MARK_RESULT",
        ]
        EWERequest.lgf("dictionary", paramet4, .get) { [weak self] (data) in
            self?.zsjgArr = data["result"] as? [[String: Any]] ?? []
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    // 整段标注
    func zdBiaoZhu(_ markOption: [String], _ remark: String) {
        let paramet: [String: Any] = [
            "markOption": markOption.joined(separator: ","),
            "markRemark": remark
        ]
        var mt: String = ""
        if self.stype == 1 {
            mt = "label/" + self.labelId
        } else if self.stype == 2 {
            mt = "audit/" + self.auditId
        } else if self.stype == 3 {
            mt = "arbitration/" + self.arbitrationId
        }
        EWERequest.lgf(mt + "/sample/" + self.id + "/mark/" + self.bzModel.markId, paramet, .put, JSONEncoding.default) { [weak self] (data) in
            self?.bzModel.markOption = markOption
            self?.bzModel.remark = remark
            SVProgressHUD.showSuccess("整段标注成功")
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    // 框选标注
    func kxBiaoZhu(_ markOption: [String], _ remark: String) {
        let kx: CGFloat = kxbzv.lgf_X * 60000
        let kw: CGFloat = kxbzv.lgf_Width * 60000
        let top: CGFloat = CGFloat(kxbzv.lgf_Y / ph_view_i.lgf_Height)
        let height: CGFloat = CGFloat(kxbzv.lgf_Height / ph_view_i.lgf_Height)
        let duration1: Int = Int(kx / self.ph_view_i_w)
        let duration2: Int = Int((kx / self.ph_view_i_w) + (kw / self.ph_view_i_w))
        let dict: [String: Any] = [
            "markOption": markOption,
            "markRemark": remark,
            "id": Date().lgf_TimeStampString(),
            "zoom": xf,
            "top": top,
            "height": height,
            "duration": [
                duration1,
                duration2
            ],
            "backgroundColor": "#FFFF00",
        ]
        self.bzModel.coordinate.append(dict)
        self.kxBiaoZhuR { [weak self] in
            SVProgressHUD.showSuccess("框选标注成功")
            self?.kxbz_l.text = "框选标注"
            self?.kxbzv.removeFromSuperview()
            self?.kxbzv = nil
        }
    }
    func kxBiaoZhuR(_ call: @escaping () -> Void) {
        let paramet: [String: Any] = [
            "coordinate": String.lgf_JsonFrom(self.bzModel.coordinate ?? [:])
        ]
        var mt: String = ""
        if self.stype == 1 {
            mt = "label/" + self.labelId
        } else if self.stype == 2 {
            mt = "audit/" + self.auditId
        } else if self.stype == 3 {
            mt = "arbitration/" + self.arbitrationId
        }
        EWERequest.lgf(mt + "/sample/" + self.id + "/mark/" + self.bzModel.markId, paramet, .put, JSONEncoding.default) { [weak self] (data) in
            if self?.bzModel != nil {
                self?.creatCoordinate([self!.bzModel!.coordinate])
            }
            call()
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    func pfR(_ paramet: [String: Any], _ call: @escaping () -> Void) {
        let mt: String = "label/" + self.auditId
        EWERequest.lgf(mt + "/sample/" + self.id + "/mark/" + self.bzModel.markId, paramet, .put, JSONEncoding.default) { (data) in
            call()
            SVProgressHUD.showSuccess("评分成功")
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    func wczcPost(_ diagnosis: [String]) {
        if self.bzModel.coordinate.count == 0 {
            SVProgressHUD.showError("请先进行整段标注")
        }
        let paramet: [String: Any] = [
            "diagnosis": diagnosis.joined(separator: ","),
        ]
        let mt: String = "arbitration/" + self.arbitrationId
        EWERequest.lgf(mt + "/sample/" + self.id + "/mark/" + self.bzModel.markId, paramet, .put, JSONEncoding.default) { [weak self] (data) in
            self?.bzModel.diagnosis = diagnosis
            let paramet2: [String: Any] = [
                "status": 20,
                "sampleId": self?.id ?? ""
            ]
            EWERequest.lgf("arbitration/" + self!.arbitrationId, paramet2, .put, JSONEncoding.default) { [weak self] (data) in
                self?.type = 6
                SVProgressHUD.showSuccess("完成仲裁")
                Timer.lgf_After(S: 0.5) {
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadTzbzshVC"), object: nil)
                    self?.navigationController?.popViewController(animated: true)
                }
            } _: { (error) in
                SVProgressHUD.showError(error)
            }
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    func wcbzPost(_ diagnosis: [String]) {
        if self.bzModel.coordinate.count == 0 {
            SVProgressHUD.showError("请先进行整段标注")
        }
        var ndiagnosis = diagnosis
        var isDifficult: Bool = false
        if ndiagnosis.contains("疑难样本") {
            isDifficult = true
            ndiagnosis.lgf_Remove("疑难样本")
        }
        var isSame: Bool = false
        if ndiagnosis.contains("听诊结果与心超报告不符") {
            isSame = true
            ndiagnosis.lgf_Remove("听诊结果与心超报告不符")
        }
        let paramet: [String: Any] = [
            "isSame": isSame ? 1 : 0,
            "isDifficult": isDifficult ? 1 : 0,
            "diagnosis": ndiagnosis.joined(separator: ","),
        ]
        let mt: String = "label/" + self.labelId
        EWERequest.lgf(mt + "/sample/" + self.id + "/mark/" + self.bzModel.markId, paramet, .put, JSONEncoding.default) { [weak self] (data) in
            self?.bzModel.diagnosis = diagnosis
            let paramet2: [String: Any] = [
                "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
            ]
            EWERequest.lgf(mt + "/user/" + EWEUser.lgf.userId + "/sample/" + self!.id, paramet2, .put, JSONEncoding.default) { [weak self] (data) in
                self?.type = 1
                SVProgressHUD.showSuccess("完成标注")
                Timer.lgf_After(S: 0.5) {
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadTzbzshVC"), object: nil)
                    self?.navigationController?.popViewController(animated: true)
                }
            } _: { (error) in
                SVProgressHUD.showError(error)
            }
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    func wcshPost(_ diagnosis: [String], _ isZc: Bool) {
        if self.bzModel.coordinate.count == 0 {
            SVProgressHUD.showError("请先进行整段标注")
        }
        let paramet: [String: Any] = [
            "diagnosis": diagnosis.joined(separator: ","),
        ]
        let mt: String = "audit/" + self.auditId
        EWERequest.lgf(mt + "/sample/" + self.id + "/mark/" + self.bzModel.markId, paramet, .put, JSONEncoding.default) { [weak self] (data) in
            self?.bzModel.diagnosis = diagnosis
            let paramet2: [String: Any] = [
                "arbitration": isZc ? 1 : 0,
            ]
            EWERequest.lgf(mt + "/user/" + EWEUser.lgf.userId + "/sample/" + self!.id, paramet2, .put, JSONEncoding.default) { [weak self] (data) in
                self?.type = 3
                SVProgressHUD.showSuccess("完成审核")
                Timer.lgf_After(S: 0.5) {
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadTzbzshVC"), object: nil)
                    self?.navigationController?.popViewController(animated: true)
                }
            } _: { (error) in
                SVProgressHUD.showError(error)
            }
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    func ybzfDelete() {
        let paramet: [String: Any] = [
            "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
        ]
        EWERequest.lgf("arbitration/" + self.arbitrationId, paramet, .delete) { [weak self] (data) in
            SVProgressHUD.showSuccess("作废成功")
            Timer.lgf_After(S: 0.5) {
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadTzbzshVC"), object: nil)
                self?.navigationController?.popViewController(animated: true)
            }
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
}
